 package com.gmrz.uaf.crypto.internal.keyFormats;
 
 import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERInteger;

import com.gmrz.uaf.crypto.CryptoConstants;
 
 public class UAFAlgKeyRSA2048PSSDer extends UAFKeyFmt
 {
   private static final Logger LOG = LogManager.getLogger(UAFAlgKeyRSA2048PSSDer.class);
 
   public UAFAlgKeyRSA2048PSSDer()
   {
     super(CryptoConstants.UAFAlgkey.UAF_ALG_KEY_RSA_2048_PSS_DER);
   }
 
   public PublicKey getKey(byte[] pubKey, int algoSuite)
     throws GeneralSecurityException
   {
     KeyFactory factory = KeyFactory.getInstance(this.uafAlgKey.getKeyAlgo());
 
     ASN1Sequence sequence = ASN1Sequence.getInstance(pubKey);
 
     if (sequence.size() != 2) {
       throw new GeneralSecurityException("Public key is not a DER encoded SEQUENCE { n INTEGER, e INTEGER }.");
     }
 
     DERInteger nDER = (DERInteger)sequence.getObjectAt(0);
     DERInteger eDER = (DERInteger)sequence.getObjectAt(1);
 
     BigInteger n = nDER.getPositiveValue();
 
     BigInteger e = eDER.getPositiveValue();
 
     byte[] nba = n.toByteArray();
     byte[] eba = e.toByteArray();
     LOG.debug("Decoded N({}) - {}", Integer.valueOf(nba.length), Arrays.toString(nba));
     LOG.debug("Decoded E({}) - {}", Integer.valueOf(eba.length), Arrays.toString(eba));
 
     if ((nba.length > 257) || ((nba.length == 257) && (nba[0] != 0)))
     {
       throw new GeneralSecurityException("Invalid modulus length - " + nba.length);
     }
 
     RSAPublicKeySpec spec = new RSAPublicKeySpec(n, e);
     RSAPublicKey pub = (RSAPublicKey)factory.generatePublic(spec);
     return pub;
   }
 }
